/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
*/
package net.redxyz.repost.service.handler;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.redxyz.repost.resource.model.AssRepostPlanChk;
import net.redxyz.repost.resource.model.SynItemOnsale;
import net.redxyz.repost.service.dao.RepostDao;
import net.redxyz.top.repost.dbo.AssRepostPlan;
import net.redxyz.top.repost.dbo.AssRepostPlanDetail;

import org.zhiqim.kernel.control.Handler;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Ints;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 均衡调整计划每日检查新增宝贝
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class RepostPlanChkHandler implements Handler<AssRepostPlanChk>
{
    private static final Log log = LogFactory.getLog("timer.repost.log");

    public void process(AssRepostPlanChk user)
    {
        String nick = user.getNick();
        int userDb = user.getUserDb();

        try
        {
            log.info("均衡上架检查[" + nick + "]开始");
            Selector selector2 = new Selector();
            selector2.addMaybe("nick", nick);
            selector2.addOrderbyAsc("createTime");

            List<AssRepostPlan> planList = ORM.table().list(AssRepostPlan.class, selector2);
            if (planList.isEmpty())
            {
                log.info("均衡上架检查[" + nick + "]没有计划要检查");
                return;
            }

            List<SynItemOnsale> onsaleItemList = user.getItemList();
            if (onsaleItemList.size() >= 10000)
            {
                log.info("均衡上架检查[" + nick + "]宝贝数10000个，不处理");
                return;
            }

            Selector selector3 = new Selector();
            selector3.addMaybe("nick", nick);
            selector3.addOrderbyDesc("delistTime");// 倒序,时间最大的在前面

            String datetime = DateTimes.getDateTimeString();
            Set<Long> itemSet = new HashSet<Long>();
            for (AssRepostPlan plan : planList)
            {
                String planId = plan.getPlanId();
                String planTitle = plan.getPlanTitle();
                String planSellerCids = plan.getPlanSellerCids();
                boolean isModify = false;//是否有修改

                // 查出计划列表详情
                Selector selector4 = new Selector();
                selector4.addMaybe("planId", planId);
                selector4.addReplace("d", user.getUserDomain());
                List<AssRepostPlanDetail> planDetails = ORM.table().list(AssRepostPlanDetail.class, selector4);

                for (SynItemOnsale item : onsaleItemList)
                {
                    if (Validates.isEmpty(item.getSellerCids()))
                        item.setSellerCids("-1");

                    if (Validates.isNotEmpty(planSellerCids) && !Validates.isStrContainStrArr(item.getSellerCids(), planSellerCids, ","))
                        continue;

                    if (Validates.isNotEmpty(planTitle) && !Validates.isStrContainStrArr(item.getTitle(), planTitle, " "))
                        continue;

                    if (itemSet.contains(item.getNumIid()))
                        continue;

                    boolean isExists = false, isRemove = false;
                    for (AssRepostPlanDetail detail : planDetails)
                    {
                        if (detail.getNumIid() == item.getNumIid())
                        {
                            if (detail.getItemStatus() == 2)
                            {// 被排除
                                isRemove = true;
                            }
                            else if (detail.getItemStatus() == 3)
                            {// 如果在计划中，且是已下架状态，现在上架了，则加入调整
                                updatePlanDetailing(nick, userDb, user.getUserDomain(), planId, detail.getNumIid());
                            }

                            detail.setItemNum(-1);// 临时使用,表示该宝贝匹配上了。
                            isExists = true;
                            break;
                        }
                    }

                    // 如果没有排除，则放置到宝贝集合中，优先级排后的计划要排除
                    if (!isRemove)
                        itemSet.add(item.getNumIid());

                    // 如果原计划中不存在，则新增
                    if (!isExists)
                    {
                        addPlanDetail(plan, item, nick);
                        isModify = true;
                    }
                }

                for (AssRepostPlanDetail detail : planDetails)
                {
                    if (detail.getItemNum() == -1)
                        continue;

                    if (detail.getItemStatus() == 2 && isOnsale(onsaleItemList, detail.getNumIid()))
                        continue;// 排除且未下架不处理

                    // 只有未调整的宝贝没匹配上,都作删除，保留编号处理
                    updatePlanDetaildown(nick, userDb, user.getUserDomain(), planId, detail.getNumIid(), detail.getItemSequence(), plan.getPlanDownIids());
                    isModify = true;
                }

                if(isModify)
                {
                    Updater updater = new Updater();
                    updater.addMaybe("planId", planId);
                    updater.addField("updateTime", datetime);
                    int count = ORM.table().count(AssRepostPlanDetail.class, selector4);
                    if (count != plan.getPlanItemNum())
                    {
                        updater.addField("planItemNum", count);
                    }
    
                    ORM.table().update(AssRepostPlan.class, updater);
                }
            }
            log.info("均衡上架检查[" + nick + "]成功");
        }
        catch (Exception e)
        {
            log.error("均衡上架检查[" + nick + "]异常", e);
        }
    }

    /**
     * 向原来自动上架计划中添加新的宝贝计划详情
     * @param plan 原计划
     * @param item 宝贝
     * @param nick 用户昵称
     * @throws Exception
     */
    private static void addPlanDetail(AssRepostPlan plan, SynItemOnsale item, String nick)
    {
        String planId = plan.getPlanId();
        String planDownIids = plan.getPlanDownIids();
        String dateTime = DateTimes.getDateTimeString();
        int planItemNum = plan.getPlanItemNum();

        String planWeeks = plan.getPlanWeeks();
        String planHours = plan.getPlanHours();

        try
        {
            List<int[]> pos = RepostDao.buildSequence(planWeeks, planHours);
            int[] p = null;
            int seq = -1;
            if (Validates.isNotEmpty(planDownIids))
            {// 手动排除宝贝不为空,进行取代
                String[] sequences = planDownIids.split(",");
                StringBuilder newIids = new StringBuilder();
                for (String sequence : sequences)
                {
                    if (seq != -1)
                        newIids.append(sequence).append(",");
                    else
                        seq = Ints.toInt(sequence, -1);
                }

                if (newIids.length() > 0)
                    newIids.setLength(newIids.length() - 1);

                if (seq != -1)
                {
                    p = pos.get(seq);
                }

                String newPlanDownIids = newIids.toString();
                if (!planDownIids.equals(newPlanDownIids))
                {
                    // 更新计划表，去除一个SEQUENCE
                    Updater updater = new Updater();
                    updater.addMust("planId", planId);
                    updater.addField("planDownIids", newPlanDownIids);
                    updater.addField("updateTime", dateTime);
                    updater.addField("planItemNum", planItemNum + 1);
                    ORM.table().update(AssRepostPlan.class, updater);

                    plan.setPlanDownIids(newPlanDownIids);
                }
            }

            if (seq == -1)
            {// 为空则进行新增
                seq = plan.getPlanSequence() + 1;
                p = pos.get(seq);

                // 更新计划表，SEQUENCE+1
                Updater updater = new Updater();
                updater.addMaybe("planId", planId);
                updater.addField("updateTime", dateTime);
                updater.addField("planSequence", seq);
                updater.addField("planItemNum", planItemNum + 1);
                ORM.table().update(AssRepostPlan.class, updater);

                plan.setPlanSequence(seq + 1);
            }

            int plamWeek = p[0];
            String planTime = RepostDao.buildRepostTime(p);

            AssRepostPlanDetail planDetail = new AssRepostPlanDetail();
            planDetail.setNick(nick);
            planDetail.setPlanId(planId);
            planDetail.setNumIid(item.getNumIid());
            planDetail.setCid(item.getCid());
            planDetail.setItemTitle(item.getTitle());
            planDetail.setItemPicUrl(item.getPicUrl());
            planDetail.setItemNum(item.getNum());
            planDetail.setItemStatus(1);
            planDetail.setItemSequence(seq);
            planDetail.setDelistTime(item.getDelistTime());
            planDetail.setPlanWeek(plamWeek);
            planDetail.setPlanTime(planTime);
            planDetail.setOperateStatus(0);
            planDetail.setOperateTime(null);
            planDetail.setOperateDetail(null);

            ORM.table().replace(planDetail);
        }
        catch (Exception e)
        {
            log.error("均衡上架检查[" + nick + "]插入宝贝时异常[" + planId + "][" + item.getNumIid() + "]", e);
        }
    }

    private void updatePlanDetailing(String nick, int userDb, String d, String planId, long numIid)
    {
        Updater updater = new Updater();
        updater.addMaybe("planId", planId);
        updater.addMaybe("numIid", numIid);
        updater.addField("itemStatus", 0);
        updater.addField("operateStatus", 0);
        updater.addField("operateTime", null);
        updater.addField("operateDetail", null);
        updater.addReplace("d", d);

        try
        {
            ORM.table().update(AssRepostPlanDetail.class, updater);
        }
        catch (Exception e)
        {
            log.error("均衡上架检查[" + nick + "][" + numIid + "]更新状态异常", e);
        }
    }

    private void updatePlanDetaildown(String nick, int userDb, String d, String planId, long numIid, int sequence, String planDownIids)
    {
        try
        {
            // 删除记录
            Selector selector = new Selector();
            selector.addMaybe("planId", planId);
            selector.addMaybe("numIid", numIid);
            selector.addReplace("d", d);

            ORM.table().delete(AssRepostPlanDetail.class, selector);

            // 记录到排除中
            if (Validates.isEmpty(planDownIids))
                planDownIids = "" + sequence;
            else
                planDownIids += "," + sequence;

            Updater updater = new Updater();
            updater.addMaybe("planId", planId);
            updater.addField("planDownIids", planDownIids);
            ORM.table().update(AssRepostPlan.class, updater);
        }
        catch (Exception e)
        {
            log.error("均衡上架检查[" + nick + "][" + numIid + "]删除异常", e);
        }
    }

    private boolean isOnsale(List<SynItemOnsale> onsaleItemList, long numIid)
    {
        for (SynItemOnsale item : onsaleItemList)
        {
            if (item.getNumIid() == numIid)
                return true;
        }

        return false;
    }
}
